﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using DomainModel;
using Services.Abstract;

namespace Web
{
    public partial class Users : BasePage
    {
        public IRoleService RoleService { get; set; }
        public IPermissionService PermissionService { get; set; }
        public IUserService UserService { get; set; }
        public IEmailService EmailService { get; set; }
        public IGroupService GroupService { get; set; }
        public ITimetableUnitService TimetableUnitService { get; set; }

        private Role _selectedRole = Role.None;

        protected new void Page_Load(object sender, EventArgs e)
        {
            SelectMenuItem("NavUsers");

            try
            {
                _selectedRole = RoleService.GetRoleByName(Request.QueryString["Role"]);
            }
            catch (Exception)
            {
                _selectedRole = Role.None;
            }

            if (!IsPostBack)
            {
                BindDdlRoles();

                DdlRolesFilter.Items.FindByValue(_selectedRole.ToString()).Selected = true;

                BindListViewUsers();
            }
        }

        private void BindListViewUsers()
        {
            List<User> usersList;
            if (_selectedRole == Role.None)
                usersList = UserService.GetAll();
            else
                usersList = UserService.GetUsers(_selectedRole, false);

            usersList = usersList.OrderBy(u => u.UserProfile.Fio).ToList();

            var ds = new List<object>();

            foreach (var user in usersList)
            {
                bool canApproveUsers = PermissionService.CanApproveUser(user);
                bool isAdmin = user.Role == Role.Admin;
                bool isTDW = user.Role == Role.TrainingDivisionWorker;
                bool isTeacher = user.Role == Role.Teacher;
                bool isParent = user.Role == Role.Parent;
                bool isStudent = user.Role == Role.Student;

                bool isCurator = false;
                bool isPraepostor = false;
                Group group = null;
                User parent = null;
                string teacherSubjects = "";
                if (isTeacher)
                {
                    group = GroupService.TeacherIsCurator(user);
                    isCurator = group != null;
                    teacherSubjects = TimetableUnitService.GetSubjectsByTeacher(user);
                    if (teacherSubjects != null)
                        teacherSubjects = teacherSubjects.Replace("; ", "</br>");
                }
                else if (isStudent)
                {
                    group = user.Group;
                    isPraepostor = GroupService.StudentIsPraepostor(user) != null;
                    parent = UserService.GetParent(user);
                }

                ds.Add(new
                {
                    Id = user.Id,
                    Fio = user.UserProfile.Fio,
                    Login = user.Login,
                    AvatarUrl = user.UserProfile.PhotoUrl,
                    IsAdmin = isAdmin,
                    IsTDW = isTDW,
                    IsTeacher = isTeacher,
                    TeacherSubjects = teacherSubjects,
                    IsCurator = isCurator,
                    IsStudent = isStudent,
                    ParentFio = parent == null ? "" : parent.UserProfile.Fio,
                    ParentId = parent == null ? 0 : parent.Id,
                    IsPraepostor = isPraepostor,
                    IsParent = isParent,
                    ChildName= parent == null ? "" : parent.Child.UserProfile.Fio,
                    ChildId = parent == null ? 0 : parent.Child.Id,
                    GroupName = group == null ? "" : group.Name,
                    GroupId = group == null ? 0 : group.Id,
                    ToApproveVisible = !user.Approved && canApproveUsers,
                });
            }

            ListViewUsers.DataSource = ds;
            ListViewUsers.DataBind();
        }

        private void BindDdlRoles()
        {
            DdlRolesFilter.Items.Add(new ListItem("Все", Role.None.ToString()));
            DdlRolesFilter.Items.Add(new ListItem(RoleService.GetRoleName(Role.Admin), Role.Admin.ToString()));
            DdlRolesFilter.Items.Add(new ListItem(RoleService.GetRoleName(Role.TrainingDivisionWorker), Role.TrainingDivisionWorker.ToString()));
            DdlRolesFilter.Items.Add(new ListItem(RoleService.GetRoleName(Role.Teacher), Role.Teacher.ToString()));
            DdlRolesFilter.Items.Add(new ListItem(RoleService.GetRoleName(Role.Student), Role.Student.ToString()));
            DdlRolesFilter.Items.Add(new ListItem(RoleService.GetRoleName(Role.Parent), Role.Parent.ToString()));
        }

        protected void DdlRolesFilter_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            string url = string.Format("/Users.aspx?Role={0}", DdlRolesFilter.SelectedValue);

            Response.Redirect(url);
        }

        protected void BtnApprove_OnClick(object sender, EventArgs e)
        {
            long userId;
            try
            {
                var listView = ((LinkButton)sender).Parent.Parent as ListViewDataItem;
                var dataKey = ListViewUsers.DataKeys[listView.DataItemIndex];
                userId = long.Parse(dataKey.Value.ToString());
            }
            catch (Exception)
            {
                ShowSysMsg("Возникла непредвиденная ошибка.");
                return;
            }

            var user = UserService.GetById(userId);

            if (user == null)
            {
                ShowSysMsg("Ошибка базы данных. Невозможно найти пользователя.");
                return;
            }

            try
            {
                user.Approved = true;

                UserService.SaveOrUpdate(user);

                string msgBody = "<h1>Уважаемый " + user.UserProfile.Fio + "</h1>" +
                                 "Ваша регистрация на ресурсе StudyControl подтверждена.";

                EmailService.Send(user.Email, "Регистрация на ресурсе StudyControl подтверждена", msgBody);

                BindListViewUsers();
            }
            catch (Exception ex)
            {
                ShowSysMsg(ex.Message);
            }
        }
    }
}